package com.sumainfor.pc.market.service;

import com.google.common.collect.Lists;
import com.netflix.discovery.converters.Auto;
import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.FileSubufferUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.OwnerMapper;
import com.sumainfor.pc.market.dao.ProfitMapper;
import com.sumainfor.pc.market.dao.UtilsMapper;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 业主
 * @Auther: zhlu
 * @Date: 2018/11/11 15:39
 * @Description:
 */
@Service
public class OwnerService {
    private ReentrantLock lock = new ReentrantLock(false);
    @Autowired
    OwnerMapper ownerMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    ProfitMapper ProfitMapper;

    Logger log= LoggerFactory.getLogger(OwnerService.class);

    String UUID=null;

    String ProId=null;

    /**
     * 功能描述:
     * 新增待联系业主
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/11 15:41
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean AddOwner(Map<String,Object> params){
        boolean result=false;
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                put("uuid", "OwId");
                put("database", Constants.DATA_SOURCE_TCMKT);
                put("surface", "tcmkt_owner");
            }});
            if(uuid!=null){
                int number=Integer.valueOf(uuid.get("uuid").toString());
                UUID= ComUtils.getLocalTrmSeqNum("yz",number);
            }else{
                UUID=ComUtils.getLocalTrmSeqNum("yz",0);
            }
            params.put("by",ContextUtils.getUserId());//操作人
            params.put("OwId",UUID);//项目编号等于项目名称加路号
            params.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            params.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(params);
            params.put("OwState",1);//1. 新房预约待看   2盈利预测待审核   3待收录房源
            try {
                Map<String,Object>citys=(Map<String,Object>)params.get("citys");
                params.putAll(citys);
                ownerMapper.AddOwner(params);
                result=true;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }finally {
            lock.unlock();
        }

        return result;
    }

    /**
     * 功能描述:
     * 获取待联系业主列表
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/14 21:41
     */
    public List<Map<String,Object>>getOwnerList(Map<String,Object>params){
        List<Map<String,Object>>getOwnerList=ownerMapper.getOwnerList(params);
        for(Map<String,Object> map:getOwnerList){
            if(!StringUtils.isBlank(MapUtils.getString(map,"OwBuilDing"))){
                if(StringUtils.isBlank(MapUtils.getString(map,"OwRoom"))){
                    map.put("building",map.get("OwBuilDing").toString()+"楼号");
                }else{
                    map.put("building",map.get("OwBuilDing").toString()+"楼号"+map.get("OwRoom").toString()+"室号");
                }
            }else{
                map.put("building",null);
            }

            if(!StringUtils.isBlank(MapUtils.getString(map,"OwLoculus"))){
                if(!StringUtils.isBlank(MapUtils.getString(map,"OwHall"))){
                    if(!StringUtils.isBlank(MapUtils.getString(map,"OwGuard"))){
                        map.put("house",map.get("OwLoculus").toString()+"室"+map.get("OwHall").toString()+"厅"+map.get("OwGuard").toString()+"卫");
                    }else{
                        map.put("house",map.get("OwLoculus").toString()+"室"+map.get("OwHall").toString()+"厅");
                    }
                }else{
                    map.put("house",map.get("OwLoculus").toString()+"室");
                }
            }else{
                map.put("house",null);
            }

        }
        return  getOwnerList;
    }

    /**
     * 功能描述:
     * 获取待联系业主列表
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/14 21:41
     */
    public int getOwnerListCount(Map<String,Object>params){
        int getOwnerListCount=ownerMapper.getOwnerListCount(params);
        return getOwnerListCount;
    }

    /**
     * 功能描述:
     * 根据编号查询业主待联系详情
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/15 19:17
     */
    public Map<String,Object>getOwnerMap(Map<String,Object>params){
        Map<String,Object> getOwnerMap=ownerMapper.getOwnerMap(params);
        return getOwnerMap;
    }

    /**
     * 功能描述:
     * 修改业主待联系资料
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/15 19:51
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdateOwner(Map<String,Object>params){
        boolean result=false;
        try {
            params.put("by",ContextUtils.getUserId());//操作人
            params.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            params.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(params);

            //zc
//            Map<String,Object>citys=(Map<String,Object>)params.get("citys");
//            params.putAll(citys);
            ownerMapper.UpdateOwner(params);
            result=true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 功能描述:
     * 根据编号查询列表业主待联系详情
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/16 14:40
     */
    public Map<String,Object>getOwnerMaps(Map<String,Object>params){
        Map<String,Object>getOwnerMaps=ownerMapper.getOwnerMaps(params);
        if(!StringUtils.isBlank(MapUtils.getString(getOwnerMaps,"OwBuilDing"))){
            if(StringUtils.isBlank(MapUtils.getString(getOwnerMaps,"OwRoom"))){
                getOwnerMaps.put("building",getOwnerMaps.get("OwBuilDing").toString()+"楼号");
            }else{
                getOwnerMaps.put("building",getOwnerMaps.get("OwBuilDing").toString()+"楼号"+getOwnerMaps.get("OwRoom").toString()+"室号");
            }
        }else{
            getOwnerMaps.put("building",null);
        }

        if(!StringUtils.isBlank(MapUtils.getString(getOwnerMaps,"OwLoculus"))){
            if(!StringUtils.isBlank(MapUtils.getString(getOwnerMaps,"OwHall"))){
                if(!StringUtils.isBlank(MapUtils.getString(getOwnerMaps,"OwGuard"))){
                    getOwnerMaps.put("house",getOwnerMaps.get("OwLoculus").toString()+"室"+getOwnerMaps.get("OwHall").toString()+"厅"+getOwnerMaps.get("OwGuard").toString()+"卫");
                }else{
                    getOwnerMaps.put("house",getOwnerMaps.get("OwLoculus").toString()+"室"+getOwnerMaps.get("OwHall").toString()+"厅");
                }
            }else{
                getOwnerMaps.put("house",getOwnerMaps.get("OwLoculus").toString()+"室");
            }
        }else{
            getOwnerMaps.put("house",null);
        }
        return getOwnerMaps;
    }

    /**
     * 功能描述:
     * 根据编号获取盈利预测业主资料
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/19 20:02
     */
    public Map<String,Object>getOwnerProMap(Map<String,Object>params){
        Map<String,Object>getOwnerProMap=ownerMapper.getOwnerProMap(params);
        Map<String,Object>Citys=new HashMap<String,Object>();
        Citys.put("Province",getOwnerProMap.get("Province"));
        Citys.put("City",getOwnerProMap.get("City"));
        Citys.put("District",getOwnerProMap.get("District"));
        Citys.put("Street",getOwnerProMap.get("Street"));
        getOwnerProMap.put("Citys",Citys);
        getOwnerProMap.remove("Province");
        getOwnerProMap.remove("City");
        getOwnerProMap.remove("District");
        getOwnerProMap.remove("Street");
        return getOwnerProMap;
    }

    /**
     * 功能描述: 
     * 获取业主即将到期列表
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/4 14:08
     */
    public List<Map<String,Object>>getOwnerExpiringList(Map<String,Object>params){
        List<Map<String,Object>>getOwnerExpiringList=ownerMapper.getOwnerExpiringList(params);
        if(getOwnerExpiringList.size()>0){
            for(Map<String,Object> map:getOwnerExpiringList){
                if(!StringUtils.isBlank(MapUtils.getString(map,"OwBuilDing"))){
                    if(StringUtils.isBlank(MapUtils.getString(map,"OwRoom"))){
                        map.put("building",map.get("OwBuilDing").toString()+"楼号");
                    }else{
                        map.put("building",map.get("OwBuilDing").toString()+"楼号"+map.get("OwRoom").toString()+"室号");
                    }
                }else{
                    map.put("building",null);
                }

                if(!StringUtils.isBlank(MapUtils.getString(map,"OwLoculus"))){
                    if(!StringUtils.isBlank(MapUtils.getString(map,"OwHall"))){
                        if(!StringUtils.isBlank(MapUtils.getString(map,"OwGuard"))){
                            map.put("house",map.get("OwLoculus").toString()+"室"+map.get("OwHall").toString()+"厅"+map.get("OwGuard").toString()+"卫");
                        }else{
                            map.put("house",map.get("OwLoculus").toString()+"室"+map.get("OwHall").toString()+"厅");
                        }
                    }else{
                        map.put("house",map.get("OwLoculus").toString()+"室");
                    }
                }else{
                    map.put("house",null);
                }
            }
        }
        return getOwnerExpiringList;
    }

    /**
     * 功能描述: 
     * 获取业主即将到期总数
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/4 14:08
     */
    public Integer getOwnerExpiringCount(Map<String,Object>params){
        Integer getOwnerExpiringCount=ownerMapper.getOwnerExpiringCount(params);
        return getOwnerExpiringCount;
    }

    /**
     * 功能描述: 
     * 根据业主编号、业主当前合同、盈利预测编号获取业主续签资料
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/16 17:53
     */
    public Map<String,Object>getRenewOwnerMap(Map<String,Object>params){
        Map<String,Object>getRenewOwnerMap=ownerMapper.getRenewOwnerMap(params);
        getRenewOwnerMap.put("ContractFile",new ArrayList<Map<String,Object>>());
        return getRenewOwnerMap;
    }

    /**
     * 功能描述: 
     * 判断当前业主是否可以继续续签
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/16 18:09
     */
    public Integer getRenewOwnerAllow(Map<String,Object>params){
        Integer getRenewOwnerAllow=ownerMapper.getRenewOwnerAllow(params);
        return getRenewOwnerAllow;
    }

    /**
     * 功能描述: 
     * 业主续签
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/3/16 20:05
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean RenewOwnerAddOwnerDeal(Map<String,Object>params){
        boolean result=false;
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                //获取当前盈利预测最大编号
                Map<String,Object>proId=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "ProId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_profit");
                }});
                if(proId!=null){
                    int number=Integer.valueOf(proId.get("uuid").toString());
                    ProId= ComUtils.getLocalTrmSeqNum("yl",number);
                }else{
                    ProId=ComUtils.getLocalTrmSeqNum("yl",0);
                }

                //所有新增处理
                Map<String,Object>commonInsertParms=new HashMap<String,Object>();
                commonInsertParms.put("by", ContextUtils.getUserId());//操作人
                commonInsertParms.put("ProId",ProId);
                commonInsertParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                commonInsertParms.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(commonInsertParms);

                params.putAll(commonInsertParms);
                params.put("ProType",2);//简单盈利预测
                //收房人编号（收房专员）
                params.put("HouseId",ContextUtils.getUserId());
                //续签盈利预测直接通过
                params.put("ProState",7);
                //新增盈利预测主表
                ProfitMapper.AddProfit(params);

                //获取业主合同最大编号
                Map<String,Object>uUID=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "OwDeId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_owner_deal");
                }});
                if(uUID!=null){
                    int number=Integer.valueOf(uUID.get("uuid").toString());
                    UUID= ComUtils.getLocalTrmSeqNum("yzht",number);
                }else{
                    UUID=ComUtils.getLocalTrmSeqNum("yzht",0);
                }
                params.put("OwDeId",UUID);

                //合同照片
                List<Map<String, Object>> ContractFileList = (List<Map<String, Object>>) params.get("ContractFile");
                String ContractFile = FileSubufferUtils.ListTranStringUtils(ContractFileList);
                params.put("ContractFile",ContractFile);

                //创建业主合同
                ownerMapper.AddOwnerDeal(params);

                //把该合同录入未过期之前的合同
                ownerMapper.UpdateOwnerDeal(new HashMap<String,Object>(){{
                    put("NextOwDeId",UUID);
                    put("OwDeId",params.get("Cause"));
                }});
                //原合同失效的时候需要吧当前合同联系人修改为当前合同


                //然后生成新增合同的周期账单
                result=true;
            } catch (NumberFormatException e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 功能描述: 
     * 收录业主的时候先判断当前业主路号室号是否存在
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/4/13 13:56
     */
    public Integer getOwnerPresence(Map<String,Object>params){
        Integer getOwnerPresence=ownerMapper.getOwnerPresence(params);
        return getOwnerPresence;
    }

    /**
     * 功能描述:
     * 获取所有的业主和业主合同资料
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/6/21 16:13
     */
    public List<Map<String,Object>>getOwnerDealList(){
        return ownerMapper.getOwnerDealList();
    }


    public List<Map<String,Object>> getOwDelListZTime(Map<String,Object> params){
        return ownerMapper.getOwDelListZTime(params);
    }

}
